<template>
  <div class="gantt-container">
    <div class="gantt-header">
      <toolbar
        :selected-posts="store.activePosts"
        :date-range="dateRange"
        @zoom="handleZoom"
        @date-change="handleDateChange"
        @today="handleToday"
        @focus-selected="handleFocusSelected"
        @create-post="openPostEditor"
        @create-milestone="openMilestoneDialog"
        @create-dependency="store.startDependencyCreation(store.activePosts)"
      />
      <gantt-stats />
    </div>

    <div class="gantt-content">
      <!-- 甘特图主区域 -->
      <div ref="ganttChart" class="gantt-chart" />

      <!-- 浮动组件 -->
      <post-editor
        v-if="store.showPostEditor"
        :post="store.activePosts[0]"
        :visible="store.showPostEditor"
        @save="handleSavePost"
        @close="store.showPostEditor = false"
      />
      <milestone-dialog
        v-if="store.showMilestoneDialog"
        :visible="store.showMilestoneDialog"
        @save="handleSaveMilestone"
        @close="store.showMilestoneDialog = false"
      />
      <dependency-creator v-if="store.creatingDependency && store.creatingDependency.length > 0" />
      <item-detail-dialog :detail="store.activePosts[0]" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { useGanttStore } from '@/store/modules/ganttStore';
import { useGanttEvents } from '@/components/GanttChart/composables/useGanttEvents';
import { useGanttSlots } from '@/components/GanttChart/composables/useGanttSlots';
import { useGanttPlugins } from '@/components/GanttChart/composables/useGanttPlugins';
import GSTC, { GSTCResult, Config, Items, Columns } from 'gantt-schedule-timeline-calendar';
import 'gantt-schedule-timeline-calendar/dist/style.css';
import Toolbar from './Toolbar.vue';
import PostEditor from './PostEditor.vue';
import ItemDetailDialog from './ItemDetailDialog.vue';
import MilestoneDialog from './MilestoneDialog.vue';
import DependencyCreator from './DependencyCreator.vue';
import GanttStats from './GanttStats.vue';
import type { BlogPost } from '@/components/GanttChart/types';

const store = useGanttStore();
const { loadSlots } = useGanttSlots();
const ganttChart = ref<HTMLElement | null>(null);
let gstc: GSTCResult | null = null;
let state: ReturnType<typeof GSTC.api.stateFromConfig>;
const dateRange: Ref<[Date, Date]> = ref([
  new Date(),
  new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
]);

// 初始化甘特图
const initGantt = async () => {
  try {
    if (!ganttChart.value) {
      throw new Error('Gantt chart container not found');
    }

    if (gstc) {
      gstc.destroy();
      gstc = null;
    }

    const { loadPlugins } = useGanttPlugins();

    // 使用更简单的初始配置测试
    const config: Config = {
      licenseKey:
        '====BEGIN LICENSE KEY====\nXz30bH3LxMToeI30v+ZQwITQFHSR6UXnu7GZJ3otswgzcbA4qgDi4jJRCVuiLSPymXcRXmILrWC0uogRLRZtIH3PosR6fCCzjJk7+FxFjuGhzJkqWQEuMc0HoYhOTwKedGab8wDhg8ws4TQ5RSujt1Yk9pJBDjzFRp0OL2C7JplBFvjiTiY2S96biqh2kINEksyrs5eoDBj/PF5YcdUlsr3hqn8vUT8MpUBy+4TmMe1Ojghfq8tEJdTJ09M9FVBNZJQe7J9Sj1SekMw/VAljBeIVxlN5yTSWvhbMTrBDCAwAgrzZoJzUnpV+PKUamQM6DCovVJXYYujqPpwQMCO+uA==||U2FsdGVkX19nj5FpE8qwp16ngTQuij/TNfqtJqsKLBjPK3XAwVdqmXXF1Q2kSEsYQmI2KKlYkF6XgRkWWMglOBbGADniiFSg8KHbTjcih0A=\ncdlgoD32MSR1+23x3a1Enibuk7LFN3C3zudY5lndzS6v6WsctW0kRPFLzXKTQjw/QDB1v9dE+UXvICyU4aEDJTYKK1tzOLxCgu0FvB9pLlegXd2ANQ+uxJ+2D81f//tv9TEoHtvCeA24RYIixnc3l1JzIfpaleoTvtplASty+DJMu1HurCGC1mBSCy61esizFY8mXQLafuj95SGKRLcdpTWfSv8E2jEkwjf4VlcTj2rBsNRHC4LWaPNkqUG6rxaVEtvcNbF3okmtmX2QgSjJHgTo28vPiUfNmFh6lkNLgXmM+kUDAuXL+samtE/G8rQp9TKcp4n4Mp0nKTfJqQYxrw==\n====END LICENSE KEY====',
      plugins: loadPlugins(),
      autoInnerHeight: true,
      list: {
        columns: generateColumns(),
        rows: generateRows()
      },
      chart: {
        item: {
          height: 50,
          gap: { top: 8 }
        },
        time: {
          period: 'month',
          from: dateRange.value[0].valueOf(),
          to: dateRange.value[1].valueOf(),
          zoom: 20
        },
        items: generateItems()
      },
      scroll: {
        vertical: {
          precise: true,
          byPixels: true
        }, // 垂直滚动设置
        horizontal: {
          precise: true,
          byPixels: true
        } // 水平滚动设置
      },
      slots: loadSlots()
    };

    state = GSTC.api.stateFromConfig(config);
    gstc = GSTC({
      element: ganttChart.value,
      state
    });

    // 设置事件处理器
    const { setupEventHandlers } = useGanttEvents(gstc, store);
    // setupEventHandlers();

    // 存储实例以便调试
    window.gstc = gstc;
    // 挂到状态管理
    store.setGstc(gstc);

    console.log('Gantt initialized successfully');
  } catch (error) {
    console.error('Gantt initialization failed:', error);
  }
};

const generateColumns = () => {
  const columns: Columns = {
    data: {
      [GSTC.api.GSTCID('name')]: {
        id: GSTC.api.GSTCID('name'),
        width: 200,
        data: 'name',
        header: { content: '专题' }
      },
      // [GSTC.api.GSTCID('title')]: {
      //   id: GSTC.api.GSTCID('title'),
      //   width: 200,
      //   data: ({ row, vido }) => vido.html`<div>
      //     <div class="gantt-title">${row.title}</div>
      //     <div class="gantt-subtitle">${row.author} | ${row.wordCount}字</div>
      //   </div>`,
      //   header: {
      //     content: '文章'
      //   }
      // },
      [GSTC.api.GSTCID('progress')]: {
        id: GSTC.api.GSTCID('progress'),
        data: ({ row, vido }) => vido.html`<div class="progress-bar">
          <div class="progress-fill" style="width: ${row.progress}%"></div>
          <span class="progress-text">${row.progress}%</span>
        </div>`,
        width: 80,
        header: { content: '进度' }
      },
      [GSTC.api.GSTCID('date')]: {
        id: GSTC.api.GSTCID('date'),
        data: ({ row }) => {
          const start = new Date(row.time.start);
          const end = new Date(row.time.end);
          return `${start.getMonth() + 1}.${start.getDate()}-${end.getMonth() + 1}.${end.getDate()}`;
        },
        width: 120,
        header: { content: '时间' }
      }
    }
  };
  console.log('Gantt Chart columns', columns);
  return columns;
};

const generateRows = () => {
  if (!store.topics || !store.topics.length) {
    return {};
  }
  const rows = store.topics.reduce((acc, topic) => {
    const id = GSTC.api.GSTCID(topic.id);
    acc[id] = {
      id,
      name: topic.name,
      priority: topic.priority,
      progress: topic.progress,
      time: {
        start: new Date(topic.startDate).getTime(),
        end: new Date(topic.endDate).getTime()
      }
    };
    return acc;
  }, {});
  console.log('Gantt Chart rows', rows);
  return rows;
};

const generateItems = () => {
  const items: Items = store.posts.reduce((acc, post: BlogPost) => {
    const id = GSTC.api.GSTCID(post.id);
    acc[id] = {
      sourceId: post.id,
      id,
      label: post.title,
      progress: post.progress,
      style: { background: store.getRandomColor() },
      rowId: GSTC.api.GSTCID(post.collectionId),
      wordCount: post.wordCount,
      img: getRandomFaceImage(),
      time: {
        start: post.startTime,
        end: post.endTime
      },
      dependant: post.dependant,
      startDate: post.startDate,
      endDate: post.endDate,
      classNames: ['additional-custom-class'],
      description: post.summary
    };
    return acc;
  }, {});
  console.log('Gantt Chart items', items);
  return items;
};

// 生成随机头像图片的函数
const getRandomFaceImage = () => `/static/faces/face-${Math.ceil(Math.random() * 50)}.jpg`;

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    draft: '#93c5fd',
    writing: '#fcd34d',
    review: '#a5b4fc',
    scheduled: '#c7d2fe',
    published: '#86efac',
    archived: '#d1d5db'
  };
  return colors[status] || '#d1d5db';
};

// 处理工具栏事件
const handleZoom = (level: 'hour' | 'day' | 'week' | 'month') => {
  store.setZoomLevel(level);
  // 初始化缩放级别和时间范围
  let zoom = 20;
  // let from = GSTC.api.date().startOf('month').valueOf();
  // let to = GSTC.api.date().endOf('month').valueOf();
  // 根据选择的周期设置缩放级别和时间范围
  switch (level) {
    case 'hour':
      zoom = 16;
      // from = GSTC.api.date().startOf('day').subtract(6, 'day').valueOf();
      // to = GSTC.api.date().endOf('day').add(6, 'day').valueOf();
      break;
    case 'day':
      zoom = 20;
      // from = GSTC.api.date().startOf('month').valueOf();
      // to = GSTC.api.date().endOf('month').valueOf();
      break;
    case 'week':
      zoom = 23;
      // from = GSTC.api.date().add(-1, 'month').startOf('month').valueOf();
      // to = GSTC.api.date().add(1, 'month').endOf('month').valueOf();
      break;
    case 'month':
      zoom = 26;
      // from = GSTC.api.date().add(-3, 'year').startOf('year').valueOf();
      // to = GSTC.api.date().add(3, 'year').endOf('year').valueOf();
      break;
  }

  // 更新配置中的时间选项
  state.update('config.chart.time', time => {
    time.zoom = zoom;
    // time.from = from;
    // time.to = to;
    return time;
  });
  // 更新缩放范围选择器的值
  const zoomRange = document.getElementById('zoom-range');
  // @ts-ignore
  if (zoomRange) zoomRange.value = zoom;
};

const handleDateChange = ({ start, end }: { start: Date; end: Date }) => {
  console.log('Gantt Chart date changed', start, end);
  // 更新配置中的时间选项
  state.update('config.chart.time', time => {
    time.from = start.getTime();
    time.to = end.getTime();
    return time;
  });
};

const handleToday = () => {
  const today = new Date();
  gstc?.api.scrollToTime(
    today.valueOf(), // 目标时间的时间戳
    true // 是否平滑滚动
  );
};

const handleFocusSelected = (post: BlogPost) => {
  gstc?.api.scrollToTime(
    post.startTime, // 目标时间的时间戳
    true // 是否平滑滚动
  );
};

// 处理文章保存
const handleSavePost = async (postData: BlogPost) => {
  try {
    if (postData.id) {
      await store.updatePost(postData);
    } else {
      await store.createPost(postData);
    }
    // refreshGantt();
    refreshGanttItems();
  } catch (error) {
    console.error('Failed to save post:', error);
  }
};

// 处理里程碑保存
const handleSaveMilestone = async (milestoneData: any) => {
  try {
    await store.saveMilestone(milestoneData);
    refreshGantt();
  } catch (error) {
    console.error('Failed to save milestone:', error);
  }
};

const refreshGanttItems = () => {
  if (!gstc) return;

  const items: Items = store.posts.reduce((acc, post) => {
    const id = GSTC.api.GSTCID(post.id);
    acc[id] = {
      sourceId: post.id,
      id,
      label: post.title,
      progress: post.progress,
      style: { background: store.getRandomColor() },
      rowId: GSTC.api.GSTCID(post.topic),
      wordCount: post.wordCount,
      img: getRandomFaceImage(),
      time: {
        start: post.startTime,
        end: post.endTime
      },
      startDate: post.startDate,
      endDate: post.endDate,
      classNames: ['additional-custom-class'],
      description: post.summary
    };
    return acc;
  }, {});
  // 更新项目数据
  state.update('config.chart.items', items);
};

// 刷新甘特图数据
const refreshGantt = () => {
  if (!gstc) return;

  gstc.updateConfig({
    list: {
      rows: store.posts.map(post => ({
        id: GSTC.api.GSTCID(post.id),
        label: post.title,
        progress: post.progress,
        status: post.status,
        time: {
          start: new Date(post.startDate).getTime(),
          end: new Date(post.endDate).getTime()
        },
        style: {
          background: getStatusColor(post.status),
          color: '#1f2937',
          'font-weight': '500'
        }
      }))
    },
    chart: {
      milestones: store.milestones.map(milestone => ({
        id: milestone.id,
        rowId: milestone.postId || 'milestones',
        label: milestone.name,
        time: new Date(milestone.date).getTime(),
        meta: {
          isMilestone: true,
          priority: milestone.priority,
          description: milestone.description
        }
      })),
      dependencies: store.dependencies.map(dep => ({
        id: dep.id,
        from: dep.sourcePost,
        to: dep.targetPost,
        type: dep.relationType
      }))
    }
  });
};

onMounted(async () => {
  try {
    await store.fetchTopics();
    await store.fetchPosts(dateRange.value[0], dateRange.value[1]);
    await store.fetchMilestones();
    await store.fetchDependencies();
    await nextTick(); // 确保DOM更新完成
    initGantt();

    // 监听依赖关系删除事件
    window.addEventListener('gantt-dependency-removed', refreshGantt);
    // 监听依赖关系添加事件
    window.addEventListener('gantt-dependency-added', refreshGantt);
  } catch (error) {
    console.error('Failed to load gantt data:', error);
  }
});

onBeforeUnmount(() => {
  if (gstc) {
    gstc.destroy();
  }

  // 移除事件监听器
  window.removeEventListener('gantt-dependency-removed', refreshGantt);
  window.removeEventListener('gantt-dependency-added', refreshGantt);
});

// 新增的方法
const openPostEditor = () => {
  store.showPostEditor = true;
};

const openMilestoneDialog = () => {
  store.showMilestoneDialog = true;
};
</script>

<style scoped>
.gantt-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: white;
  border-radius: 0.5rem;
  box-shadow:
    0 1px 3px 0 rgba(0, 0, 0, 0.1),
    0 1px 2px 0 rgba(0, 0, 0, 0.06);
}

.gantt-header {
  border-bottom: 1px solid #e5e7eb;
}

.gantt-content {
  flex: 1;
  position: relative;
}

.gantt-chart {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}
</style>
